package com.aaa.reflection.demo3;

import java.lang.reflect.Field;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description: 通过反射类获取属性类对象
 * @date 2022/10/27
 */
public class Test01 {
    public static void main(String[] args)throws Exception {
        //首先通过类名获取反射类对象
        Class<Dog> dogClass = Dog.class;
        //1获取本类中指定的属性对象
        Field sleep = dogClass.getDeclaredField("sleep");
        System.out.println("sleep0 = " + sleep);
        Field each = dogClass.getDeclaredField("each");
        System.out.println("each = " + each);

        //2获取所有的属性
        Field[] declaredFields = dogClass.getDeclaredFields();
        for (Field field:declaredFields) {
            System.out.println("field = " + field);
        }

        //3获取本类以及父类中指定的public属性
        Field sleep1 = dogClass.getField("sleep");
        System.out.println("sleep1 = " + sleep1);

        //Exception in thread "main" java.lang.NoSuchFieldException: each
        //不能获取私有属性只能获取公共属性
//        Field each1 = dogClass.getField("each");
//        System.out.println("each1 = " + each1);
        Field job = dogClass.getField("job");
        System.out.println("job = " + job);

        //4获取本类及其父类中的所有公共属性
        Field[] fields = dogClass.getFields();
        for (Field field:fields) {
            System.out.println("field = " + field);
        }

    }
}

class Cat{
    public String job;
    private Integer age;
}
class Dog extends Cat{
    public String sleep;
    private Integer each;

    @Override
    public String toString() {
        return "Dog{" +
                "sleep='" + sleep + '\'' +
                ", each=" + each +
                '}';
    }
}
